﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using PPAP.BO;
using PPAP.Model;
using System.Configuration;
using System.IO;

namespace PPAP.Web.Todolist
{
    public partial class Inspection : PageBase
    {
        SamplecardBO sbo = new SamplecardBO();
        SampleCardTaskBO stbo = new SampleCardTaskBO();
        T_FileBO manager = new T_FileBO();
        MailTemplateBO mbo = new MailTemplateBO();
        LogBO lbo = new LogBO();
        UsersBO ubo = new UsersBO();
        public string RID { get; set; }
        public string FJID { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["SID"] != null&&Request.QueryString["RID"]!=null)
            {
               if (Request.QueryString["status"] != null && Request.QueryString["status"].ToString() == "1")
                {
                    btnApprove.Visible = true;
                    btnReject.Visible = true;
                    trReason.Visible = true;
                }
                RID = Request.QueryString["RID"].ToString();
                if (!Page.IsPostBack)
                {
                    Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));

                    DataSet ds2 = stbo.GetList(" s.sid=" + Request.QueryString["SID"].ToString());
                    if (ds2.Tables[0].Rows.Count == 0)
                    {
                        DataRow dr = ds2.Tables[0].NewRow();
                        dr[3] = "No data";
                        ds2.Tables[0].Rows.Add(dr);
                    }
                    GridView2.DataSource = ds2;
                    GridView2.DataBind();

                    if (sa != null)
                    {
                        DataSet ds1 = sbo.GetSampleCardName(sa.ID);
                        if (ds1.Tables[0].Rows.Count > 0)
                        {
                            lblCardNo.Text = ds1.Tables[0].Rows[0][0].ToString();
                            lblDepartment.Text = ds1.Tables[0].Rows[0][1].ToString();
                            //if (lblDepartment.Text.Trim() == "Quality Management")
                            //    tr1.Visible = true;
                            //else if (lblDepartment.Text.Trim() == "Process")
                            //    tr2.Visible = true;
                            //else if (lblDepartment.Text.Trim() == "R&D Testing")
                            //    tr3.Visible = true;
                            //else if (lblDepartment.Text.Trim() == "R&D Development")
                            //    tr4.Visible = true;
                            //else if (lblDepartment.Text.Trim() == "Colour")
                            //    tr5.Visible = true;
                            //else
                            //    Table1.Visible = false;
                            //td1.InnerHtml = ds1.Tables[0].Rows[0]["remark"].ToString();
                            Label9.Text = ds1.Tables[0].Rows[0]["remark"].ToString();
                            //td1.Disabled = true;
                        }
                        FJID = sa.Inspectionreportid;
                        lblUp.Text = "<input type='button'   class='button' onclick='javascript:PopUpWindow(\"UploadFile.aspx?RID=" + RID + "&FJID=" + FJID +"&filetype=Inspection"+ "\", 230, 160, 730, 350);'   value='Upload'/>";
                        rbtR.Checked = sa.RESULT == "R" ? true : false;
                        rbtY.Checked = sa.RESULT == "Y" ? true : false;
                        rbtG.Checked = sa.RESULT == "G" ? true : false;
                        txtInternalComment.Text = sa.Internalcomment;
                        txtReason.Text = sa.Reason;
                        txtReason2.InnerHtml = sa.Reason.Replace("\r\n", "<br>");
                        if (sa.STATUS != 0&&sa.STATUS!=2)
                        {
                            Button2.Visible = false;
                            //btnUp.Visible = false;
                            lblUp.Visible = false;
                            rbtG.Enabled = false;
                            rbtR.Enabled = false;
                            rbtY.Enabled = false;
                            txtInternalComment.Enabled = false;
                            txtReason.Visible = false;
                            txtReason2.Visible = true;
                            trfile.Visible = false;
                        }
                        else
                        {
                            btnApprove.Visible = false;
                            btnReject.Visible = false;
                        }
                        if (Request.QueryString["his"] != null && Request.QueryString["his"].ToString() == "1")
                        {
                            Button2.Visible = false;
                            //btnUp.Visible = false;
                            lblUp.Visible = false;
                            rbtG.Enabled = false;
                            rbtR.Enabled = false;
                            rbtY.Enabled = false;
                            txtInternalComment.Enabled = false;
                            txtReason.Visible = false;
                            txtReason2.Visible = true;
                            trfile.Visible = false;
                            btnApprove.Visible = false;
                            btnReject.Visible = false;
                            GridView1.Columns[5].Visible = false;
                        }

                        DataSet ds = manager.GetFileList(sa.Inspectionreportid);
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            DataRow dr = ds.Tables[0].NewRow();
                            dr["F_Filename"] = "<font color='red'>No files available</font>";
                            ds.Tables[0].Rows.Add(dr);
                        }
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
                }
            }
            if (Request.QueryString["deid"] != null)
            {
                DeleteFile(Request.QueryString["deid"].ToString());
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fileid"></param>
        private void DeleteFile(string fileid)
        {
            try
            {
                DataSet ds = manager.Getpath(int.Parse(fileid));
                string path = ds.Tables[0].Rows[0]["F_Detail"].ToString();

                if (manager.DeleteFile(fileid))
                {
                    // File.Delete(path);
                    DataSet dd = sbo.GetList(" Inspectionreportid='" + ds.Tables[0].Rows[0]["F_FILEID"].ToString() + "'");
                    lbo.WriteLog(CurrentUser.Id, "Delete file(FinalDecisions):" + ds.Tables[0].Rows[0]["f_filename"].ToString(), dd.Tables[0].Rows[0]["ID"].ToString());
                    AlertRedirect("Deleted successful", "Inspection.aspx?RID=" + dd.Tables[0].Rows[0]["PPARID"].ToString()+"&SID="+dd.Tables[0].Rows[0]["ID"].ToString());
                    //AlertBack("Deleted successful");
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Submit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString["SID"] != null)
                {
                    if (!rbtG.Checked && !rbtR.Checked && !rbtY.Checked)
                    {
                        AlertMessage("Please select result.");
                        return;
                    }
                    Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
                    if (sa != null)
                    {
                        sa.RESULT = rbtG.Checked ? "G" : rbtR.Checked ? "R" : rbtY.Checked ? "Y" : "";
                        sa.STATUS = 1;   //0待检测 1Submit待审核  2审核退回 3审核通过
                        sa.ENDTIMEACTUAL = DateTime.Now;
                        sa.Internalcomment = CheckWord(txtInternalComment.Text);
                        sa.Reason = CheckWord(txtReason.Text);
                        sbo.Update(sa);

                        Users u = ubo.GetModelByUserName(CurrentUser.Id);
                        if (u != null && (u.POSITION == "SQ Manager" || u.POSITION == "SQE" || u.POSITION == "BDNT/Q Vice President"))
                        {
                            Approve(false);
                        }
                        else
                        {

                            //发邮件

                            MailTemplate mail = mbo.GetModel(8);
                            DataSet dsmail = mbo.GetEDM8(sa.ID.ToString());
                            if (mail != null && dsmail.Tables[0].Rows.Count > 0)
                            {
                                string title = mail.TITLE.Replace("{Part No.}", dsmail.Tables[0].Rows[0]["bdntpartno"].ToString());
                                title = title.Replace("{Part name}", dsmail.Tables[0].Rows[0]["bdntpartname"].ToString());
                                title = title.Replace("{Sample card}", dsmail.Tables[0].Rows[0]["testitemname"].ToString());
                                title = title.Replace("{Color}", dsmail.Tables[0].Rows[0]["color"].ToString());
                                try
                                {
                                    base.SendEmailToUser(dsmail.Tables[0].Rows[0]["email"].ToString(), title, mail.CONTENT.Replace("{Sample card}", dsmail.Tables[0].Rows[0]["testitemname"].ToString()), null);
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + dsmail.Tables[0].Rows[0]["email"].ToString(), Request.QueryString["rid"].ToString());

                                }
                                catch (Exception ex)
                                {
                                    AlertMessage(ex.Message.ToString());
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + ex.Message.ToString(), Request.QueryString["rid"].ToString());
                                }
                            }

                            DataSet dsmail2 = mbo.GetEDM82(sa.ID.ToString());
                            if (mail != null && dsmail2.Tables[0].Rows.Count > 0)
                            {
                                string title = mail.TITLE.Replace("{Part No.}", dsmail2.Tables[0].Rows[0]["bdntpartno"].ToString());
                                title = title.Replace("{Part name}", dsmail2.Tables[0].Rows[0]["bdntpartname"].ToString());
                                title = title.Replace("{Sample card}", dsmail2.Tables[0].Rows[0]["testitemname"].ToString());
                                title = title.Replace("{Color}", dsmail2.Tables[0].Rows[0]["color"].ToString());
                                try
                                {
                                    base.SendEmailToUser(dsmail2.Tables[0].Rows[0]["email"].ToString(), title, mail.CONTENT.Replace("{Sample card}", dsmail2.Tables[0].Rows[0]["testitemname"].ToString()), null);
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + dsmail2.Tables[0].Rows[0]["email"].ToString(), Request.QueryString["rid"].ToString());

                                }
                                catch (Exception ex)
                                {
                                    AlertMessage(ex.Message.ToString());
                                    lbo.WriteLog(CurrentUser.Id, "Send Email:" + ex.Message.ToString(), Request.QueryString["rid"].ToString());
                                }
                            }

                            //发邮件

                            Button2.Visible = false;
                            //btnUp.Visible = false;
                            lblUp.Visible = false;
                            rbtG.Enabled = false;
                            rbtR.Enabled = false;
                            rbtY.Enabled = false;
                            txtInternalComment.Enabled = false;
                            txtReason.Enabled = false;
                            if (Request.QueryString["RID"] != null)
                                lbo.WriteLog(CurrentUser.Id, "Submit (Inspection)", Request.QueryString["RID"].ToString());
                            AddSampleCardTask("Engineer decided");
                            //Response.Write("<script>window.parent.frames['menu'].location.reload();</script>");

                        }
                        Response.Write("<script language=javascript>top.frames['menu'].location.reload();</script>");
                        Response.Write("<script>top.frames['mainFrame'].location='SampleCard.aspx'</script>");
                    }
                }
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 保存流程记录
        /// </summary>
        /// <param name="Reamrk"></param>
        private void AddSampleCardTask(string Reamrk)
        {
            SampleCardTask task = new SampleCardTask();
            task.CREATETIME = DateTime.Now;
            task.CREATEUSER = CurrentUser.Id;
            task.REAMRK = Reamrk;
            task.SID = int.Parse(Request.QueryString["SID"].ToString());
            stbo.Add(task);
        }

        /// <summary>
        /// Approve
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnApprove_Click(object sender, EventArgs e)
        {
            Approve(true);
            Response.Write("<script language=javascript>top.frames['menu'].location.reload();</script>");
            Response.Write("<script>top.frames['mainFrame'].location='Approval.aspx'</script>");
        }

        /// <summary>
        /// 审核通过
        /// </summary>
        private void Approve(bool app)
        {
            if (Request.QueryString["SID"] != null)
            {
                Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
                if (sa != null)
                {
                    if ((sa.STATUS == 1&&ubo.IsGermany(CurrentUser.Id) )&&app)  //如果是TE提交并且登录人员为德国人
                    {
                        sa.STATUS = 4;

                    }
                    else if ((sa.STATUS == 1 && !ubo.IsGermany(CurrentUser.Id)) && app)  //如果是TE提交并且登录人员不是德国人
                    {
                        sa.STATUS = 5;

                    }
                    else    //否则为中方TM提交，有德方TM审批
                        sa.STATUS = 3;
                    sa.ENDTIMEACTUAL = DateTime.Now;
                    sbo.Update(sa);
                    btnApprove.Visible = false;
                    btnReject.Visible = false;

                    if (sbo.CheckSampleCardPass(int.Parse(sa.ID.ToString()))) //全部通过检测后，发邮件通知QE
                    {
                        MailTemplate mail = mbo.GetModel(9);
                        DataSet dsmail = mbo.GetEDM9(sa.ID.ToString());
                        if (mail != null && dsmail.Tables[0].Rows.Count > 0)
                        {
                            string title = mail.TITLE.Replace("{Part No.}", dsmail.Tables[0].Rows[0]["bdntpartno"].ToString());
                            title = title.Replace("{Part name}", dsmail.Tables[0].Rows[0]["bdntpartname"].ToString());
                            title = title.Replace("{Color}", dsmail.Tables[0].Rows[0]["color"].ToString());
                            try
                            {
                                base.SendEmailToUser(dsmail.Tables[0].Rows[0]["email"].ToString(), title, mail.CONTENT, null);
                                lbo.WriteLog(CurrentUser.Id, "Send Email:" + dsmail.Tables[0].Rows[0]["email"].ToString(), Request.QueryString["rid"].ToString());

                            }
                            catch (Exception ex)
                            {
                                AlertMessage(ex.Message.ToString());
                                lbo.WriteLog(CurrentUser.Id, "Send Email:" + ex.Message.ToString(), Request.QueryString["rid"].ToString());
                            }
                        }
                    }
                    //
                    PPAR p = new PPARBO().GetModel(int.Parse(sa.PPARID.ToString()));
                    p.STATUS = 6;
                    new PPARBO().UpdateForSupplier(p);
                    p.FINALRESULT = "";
                    new PPARBO().UpdateForFINALRESULT(p);
                    lbo.WriteLog(CurrentUser.Id, "Approve (Inspection)", p.ID.ToString());
                    AddSampleCardTask("Manager approved");
                    
                }
            }
        }

        /// <summary>
        /// Reject
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["SID"] != null)
            {
                if (txtResaon2.Text.Trim() == "")
                {
                    AlertMessage("Please input reason for rejection");
                    return;
                }
                else
                {
                    txtResaon2.Text = CheckWord(txtResaon2.Text);
                    Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
                    if (sa != null)
                    {
                        //if (sa.STATUS == 1||sa.STATUS==5)//如果由TE提交或德方TM退回，则由中方TM审批
                        sa.STATUS = 2;
                        //else  //否则由中方TM提交，有德方TM审批
                        //    sa.STATUS = 5;
                        sbo.Update(sa);

                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        if (Request.QueryString["RID"] != null)
                            lbo.WriteLog(CurrentUser.Id, "Reject (Inspection)", Request.QueryString["RID"].ToString());
                        AddSampleCardTask("Manager rejected:"+txtResaon2.Text);
                        Response.Write("<script language=javascript>top.frames['menu'].location.reload();</script>");
                        Response.Write("<script>top.frames['mainFrame'].location='Approval.aspx'</script>");
                    }
                }
            }
        }

        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string GetLink(string filename)
        {
            //string filepath = "ftp://" + ConfigurationManager.AppSettings["ftpServerIP"] + "/";
            string filepath = ConfigurationManager.AppSettings["FilePath"];
            return filepath + filename;
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            if (File.Exists(ConfigurationManager.AppSettings["FilePath"] + link.ToolTip))
            {
                FileInfo file = new FileInfo(ConfigurationManager.AppSettings["FilePath"] + link.ToolTip);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name.Length > 14 ? file.Name.Substring(14, file.Name.Length - 14) : file.Name)); //解决中文文件名乱码    
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
                AlertMessage("File does not exist");
        }

        protected void txtReason_TextChanged(object sender, EventArgs e)
        {
            if (Request.QueryString["SID"] != null)
            {
                Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
                if (sa != null)
                {
                    sa.RESULT = rbtG.Checked ? "G" : rbtR.Checked ? "R" : rbtY.Checked ? "Y" : "";
                    sa.Internalcomment = txtInternalComment.Text;
                    sa.Reason = txtReason.Text;
                    sbo.Update(sa);
                }
            }
        }

        protected void txtInternalComment_TextChanged(object sender, EventArgs e)
        {
            if (Request.QueryString["SID"] != null)
            {
                Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
                if (sa != null)
                {
                    sa.RESULT = rbtG.Checked ? "G" : rbtR.Checked ? "R" : rbtY.Checked ? "Y" : "";
                    sa.Internalcomment = txtInternalComment.Text;
                    sa.Reason = txtReason.Text;
                    sbo.Update(sa);
                }
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button3_Click(object sender, EventArgs e)
        {
            Button3.Visible = false;
            Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
            if (sa != null)
            {
                DataSet ds1 = sbo.GetSampleCardName(sa.ID);
                if (ds1.Tables[0].Rows.Count > 0)
                {
                    lblCardNo.Text = ds1.Tables[0].Rows[0][0].ToString();
                    lblDepartment.Text = ds1.Tables[0].Rows[0][1].ToString();
                }
                FJID = sa.Inspectionreportid;
                if (Request.QueryString["RID"] != null )
                {
                    string FileName = file.FileName;
                    if (!string.IsNullOrEmpty(FileName))
                    {
                        string a = FileName;
                        bool check = false;
                        foreach (char b in a)
                        {
                            if (b > 255)  //小于255的为英文字符，大于255的则为中文字符
                            {
                                check = true;
                            }

                        }
                        //判断文件名中是否存在中文字符
                        if (check)  //如果文件名中存在中文字符，则提示不能上传
                        {
                            Button3.Visible = true;
                            AlertMessage(" File name can not contain Chinese characters!");
                            return;
                        }
                        string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
                        if ((extension.ToLower() == ".pdf"))
                        {
                            int fileSize = file.PostedFile.ContentLength;
                            if (fileSize == 0)
                            {
                                base.AlertMessage("The file does not exist！");
                            }
                            else
                            {
                                if (true)//限制大小为1M
                                {
                                    string filepath = ConfigurationManager.AppSettings["FilePath"];   //从配置文件中获取文件存放路径
                                    string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    string FileNam_Time = "";
                                    int FileIndex = FileName.LastIndexOf("\\");
                                    string FName = FileName.Substring(FileIndex + 1);
                                    string url = time + FName;
                                    FileNam_Time = FName;//日期和名称组合
                                    if (!Directory.Exists(filepath))
                                    {
                                        System.IO.Directory.CreateDirectory(filepath);
                                    }
                                    file.SaveAs(filepath + time + FileNam_Time);

                                    DataInfo(FJID, FileNam_Time, filepath + time, 0, url, (fileSize / 1024.0).ToString("n") + "kb", "", CurrentUser.Id, "Inspection", Request.QueryString["rid"] == null ? "" : Request.QueryString["rid"].ToString(), "01");

                                    lbo.WriteLog(CurrentUser.Id, "Upload File:" + FName, Request.QueryString["RID"].ToString());


                                    DataSet ds = manager.GetFileList(sa.Inspectionreportid);
                                    if (ds.Tables[0].Rows.Count == 0)
                                    {
                                        DataRow dr = ds.Tables[0].NewRow();
                                        dr["F_Filename"] = "<font color='red'>No files available</font>";
                                        ds.Tables[0].Rows.Add(dr);
                                    }
                                    GridView1.DataSource = ds;
                                    GridView1.DataBind();
                                }
                            }
                        }
                        else
                        {
                            AlertMessage("Can't upload this file types,Please select a PDF file");
                        }
                    }
                    else
                    {
                        AlertMessage("Please select accessories！");
                    }
                }
            }
            Button3.Visible = true;
        }

        //添加操作
        private void DataInfo(string F_FileID, string F_Filename, string path, int type, string url, string filesize, string remarks, string upby, string filetype, string pparid, string fileversion)
        {
            manager.InsertFile(F_FileID, F_Filename, path, type, url, filesize, remarks, upby, filetype, pparid, fileversion);
        }

        //protected void btnUpload_Click(object sender, EventArgs e)
        //{
        //    if (!Page.IsPostBack)
        //    {
        //        RID = Request.QueryString["RID"].ToString();

        //        Samplecard sa1 = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
        //        if (sa1 != null)
        //        {
        //            FJID = sa1.Inspectionreportid;
        //        }
        //        if (Request.QueryString["SID"] != null)
        //        {
        //            Samplecard sa = sbo.GetModel(int.Parse(Request.QueryString["SID"].ToString()));
        //            if (sa != null)
        //            {
        //                sa.RESULT = rbtG.Checked ? "G" : rbtR.Checked ? "R" : "Y";
        //                sa.Internalcomment = txtInternalComment.Text;
        //                sa.Reason = txtReason.Text;
        //                sbo.Update(sa);
        //            }
        //        }
        //        Page.RegisterStartupScript("AlertMessage", "<script language='javascript'>javascript:PopUpWindow(\"UploadFile.aspx?RID=" + RID + "&FJID=" + FJID + "&filetype=Inspection" + "\", 230, 160, 730, 350);</script>");
        //    }
        //}
    }
}